package com.xiaodimall.beforesys.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaodimall.beforesys.mapper.OrderMapper;
import com.xiaodimall.beforesys.pojo.Order;
import com.xiaodimall.beforesys.pojo.User;
import com.xiaodimall.beforesys.service.PayService;
import com.xiaodimall.common.*;
import com.xiaodimall.utils.AlipayConfig;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author wyc
 * @description
 * @ClassName payServiceImpl
 * @date 2022/11/30 19:18
 */
@Service
public class PayServiceImpl implements PayService {


    //注入订单持久层对象
    @Resource
    OrderMapper orderMapper;


    /**
     * 显示支付方式和订单信息
     * @author WYC
     * @param request
     * @param orderNo
     * @param httpSession
     * @return: 选着支付方式页面
     * @date: 2022/11/30 19:03
     */
    @Override
    public String toPayTypePage(HttpServletRequest request, String orderNo, HttpSession httpSession) {
        User user = (User) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        //判断登录是否超时
        if (user == null) {
            return ServiceResultEnum.SESSION_ERROR_NULL.getResult();
        }
        Order order = orderMapper.selectByOrderNo(orderNo);
        //判断订单状态 未支付才显示订单信息
        if (order.getOrderStatus()==0) {
            //判断订单userId
            if (order.getUserId()== user.getUserId()) {
                //绑定并显示数据
                request.setAttribute("orderNo", orderNo);
                request.setAttribute("totalPrice", order.getTotalPrice());
                return "mall/pay-select";
            }
        }
        return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
    }

    @Override
    public String choosePayService(HttpSession session, String orderNo, int payType) {
        if (payType == 1) {
            Order order = orderMapper.selectByOrderNo(orderNo);
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key, "json",
                    AlipayConfig.charset,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            //这里设置支付后跳转的地址
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            // 订单编号
            String out_trade_no = orderNo;
            //付款金额
            String total_amount = order.getTotalPrice().toString();
            //订单名称，必填
            String subject =orderNo;
            //商品描述，可空
            //String body = "用户订购商品个数：" + bill.getTicketnum();
            String body = order.getExtraInfo();
            // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
            String timeout_express = "5m";

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"timeout_express\":\""+ timeout_express +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            String form = null;
            try {
                //请求
                form = alipayClient.pageExecute(alipayRequest).getBody();
                System.out.println("form:"+form);

            } catch (AlipayApiException e) {
                e.printStackTrace();
            }

            User user =(User) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
            //修改订单状态   当前用户下提交的当前这个订单的状态
            order.setOrderStatus(MallOrderStatusEnum.OREDER_PAID.getOrderStatus());
            //支付类型
            order.setPayType(PayTypeEnum.ALI_PAY.getPayType());
//            //支付状态
//            order.setPayStatus(PayStatusEnum.PAY_SUCCESS.getPayStatus());
            //支付时间
            order.setPayTime(new Date());
            //修改时间
            order.setUpdateTime(new Date());
            orderMapper.update(order, new QueryWrapper<Order>().eq("user_id", user.getUserId()).eq("order_no", orderNo));
            //这里设置支付后跳转的地址
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            return form;

        } else {

            return "mall/wxpay";
        }

    }


}
